
<template>
  <div class="question-bank-container">
    <!-- 左侧答题卡 -->
    <div class="answer-card">
      <el-card>
        <h2 class="card-title">答题卡</h2>
        <div class="question-type-section" v-for="(questions, type) in groupedQuestions" :key="type">
          <h3 class="question-type-title">{{ questionTypeLabels[type] }}</h3>
          <div class="question-list">
            <div 
              class="question-item" 
              v-for="question in questions" 
              :key="question.id"
              :class="{
                'answered': isQuestionAnswered(question.id),
                'current': currentQuestionId === question.id
              }"
              @click="scrollToQuestion(question.id)"
            >
              {{ question.id }}
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 右侧题目 -->
    <div class="question-content">
      <el-card>
        <h2 class="exam-title">{{ exam.title }}</h2>
        <p class="exam-description">{{ exam.description }}</p>
        
        <!-- 按题型展示 -->
        <div class="question-section" v-for="(questions, type) in groupedQuestions" :key="type">
          <h3 class="section-title">{{ questionTypeLabels[type] }}</h3>
          
          <div 
            class="question-wrapper" 
            v-for="question in questions" 
            :key="question.id"
            :id="'question-' + question.id"
            @click="currentQuestionId = question.id"
          >
            <div class="question-header">
              <strong class="question-number">题目 {{ question.id }}:</strong>
              <span class="question-content-text">{{ question.content }}</span>
            </div>
            
            <!-- 单选题 -->
            <div class="question-options" v-if="question.type === 'SingleChoice'"  >
              <div 
                v-for="(option, index) in question.options" 
                :key="index"
                class="option-item"
                @click="toggleSingleChoice(question.id, option)"
              >
                <el-radio 
                  :label="option"
                  v-model="userAnswers[question.id]"
                >
                  {{ option }}
                </el-radio>
              </div>
            </div>
            
            <!-- 多选题 -->
            <div class="question-options" v-if="question.type === 'MultipleChoice'">
              <div 
                v-for="(option, index) in question.options" 
                :key="index"
                class="option-item"
                @click.stop="toggleMultipleChoice(question.id, option)"
              >
                <el-checkbox 
                  :label="option"
                  :model-value="(userAnswers[question.id] || []).includes(option)"
                >
                  {{ option }}
                </el-checkbox>
              </div>
            </div>
            
            <!-- 填空题 -->
            <div class="gap-filling" v-if="question.type === 'GapFilling'">
              <el-input 
                v-model="userAnswers[question.id]" 
                placeholder="请输入答案"
                clearable
                @change="handleInputChange(question.id)"
              />
            </div>
            
            <!-- 问答题 -->
            <div class="answer-question" v-if="question.type === 'AnswerQuestion'">
              <Editor 
                class="editor" 
                ref="editorComponent" 
                v-model="userAnswers[question.id] as string"
                placeholder="请输入你的答案..."
                @change="handleInputChange(question.id)"
              />
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button type="primary" @click="saveExam">保存试卷</el-button>
          <el-button type="warning" @click="submitExam">提交试卷</el-button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { ref, computed, onMounted, defineComponent } from "vue";
import Editor from "@/components/EditorComponent.vue"
import { ElMessageBox } from "element-plus";

export default defineComponent({
  name: 'QuestionBankRandomQuiz',
})
</script>

<script lang="ts" setup>

// 定义试卷和问题的类型
interface Question {
  id: number;
  type: "SingleChoice" | "MultipleChoice" | "GapFilling" | "AnswerQuestion"; // 题型
  content: string; // 题目内容
  options?: string[]; // 选项（单选/多选题）
  answer: string | string[]; // 正确答案
  userAnswer?: string | string[]; // 用户答案
}

interface Exam {
  id: number;
  title: string;
  description: string;
  questions: Question[];
}

// 用户的答案
const userAnswers = ref<Record<number, string | string[]>>({});
// 当前显示的题目ID
const currentQuestionId = ref<number | null>(null);

// 示例试卷数据 - 完全保留您的原始数据
const exam = ref<Exam>({
  id: 1,
  title: "Vue第一次测验",
  description: "这是一个示例试卷，包含单选题、多选题、填空题和问答题。",
  questions: [
    {
      id: 1,
      type: "SingleChoice",
      content: "Vue.js 是由哪个公司/个人最初开发的？",
      options: ["Facebook", "Google", "Evan You", "Microsoft"],
      answer: "Evan You"
    },

    {
      id: 2,
      type: "SingleChoice",
      content: "Vue 的核心特性是什么？",
      options: ["组件化系统", "虚拟DOM", "响应式数据绑定", "以上都是"],
      answer: "以上都是"
    },

    {
      id: 3,
      type: "SingleChoice",
      content: "Vue 中用于声明响应式数据的选项是？",
      options: ["methods", "computed", "data", "watch"],
      answer: "data"
    },

    {
      id: 4,
      type: "SingleChoice",
      content: "Vue 中用于监听数据变化的选项是？",
      options: ["methods", "computed", "data", "watch"],
      answer: "watch"
    },

    {
      id: 5,
      type: "SingleChoice",
      content: "Vue 中用于创建组件的API是？",
      options: ["Vue.component()", "Vue.create()", "Vue.new()", "Vue.define()"],
      answer: "Vue.component()"
    },
    {
      id: 6,
      type: "SingleChoice",
      content: "Vue 中用于创建路由的API是？",
      options: ["Vue.router()", "Vue.route()", "Vue.router.create()", "Vue.router.new()"],
      answer: "Vue.router()"
    },

    {
      id: 7,
      type: "SingleChoice",
      content: "Vue 的官方状态管理库是？",
      options: ["Redux", "Vuex", "Pinia", "MobX"],
      answer: "Vuex"
    },

    {
      id: 8,
      type: "SingleChoice",
      content: "Vue 3 的 Composition API 主要解决了什么问题？",
      options: ["更好的TypeScript支持", "更好的代码组织和复用", "更好的性能", "以上都是"],
      answer: "以上都是"
    },

    {
      id: 9,
      type: "SingleChoice",
      content: "Vue 中用于条件渲染的指令是？",
      options: ["v-for", "v-if", "v-bind", "v-model"],
      answer: "v-if"
    },

    {
      id: 10,
      type: "SingleChoice",
      content: "Vue 中用于双向数据绑定的指令是？",
      options: ["v-for", "v-if", "v-bind", "v-model"],
      answer: "v-model"
    },
    {
      id: 11,
      type: "MultipleChoice",
      content: "以下哪些是 Vue 的核心特性？",
      options: ["响应式数据绑定", "组件化系统", "虚拟DOM", "双向数据绑定"],
      answer: ["响应式数据绑定", "组件化系统", "虚拟DOM", "双向数据绑定"]
    },

    {
      id: 12,
      type: "MultipleChoice",
      content: "Vue 中哪些选项可以用于处理数据逻辑？",
      options: ["data", "methods", "computed", "watch"],
      answer: ["data", "methods", "computed", "watch"]
    },

    {
      id: 13,
      type: "MultipleChoice",
      content: "以下哪些是 Vue 的生命周期钩子函数？",
      options: ["created", "mounted", "updated", "destroyed"],
      answer: ["created", "mounted", "updated", "destroyed"]
    },

    {
      id: 14,
      type: "MultipleChoice",
      content: "Vue 中哪些指令用于渲染列表？",
      options: ["v-for", "v-if", "v-show", "v-bind"],
      answer: ["v-for"]
    },

    {
      id: 15,
      type: "MultipleChoice",
      content: "以下哪些是 Vue 的全局API？",
      options: ["Vue.component", "Vue.directive", "Vue.filter", "Vue.mixin"],
      answer: ["Vue.component", "Vue.directive", "Vue.filter", "Vue.mixin"]
    },
    {
      id: 16,
      type: "GapFilling",
      content: "Vue中用于声明响应式数据的选项是 ______。",
      answer: "data"
    },

    {
      id: 17,
      type: "GapFilling",
      content: "Vue中用于创建全局组件的API是 ______。",
      answer: "Vue.component"
    },

    {
      id: 18,
      type: "GapFilling",
      content: "Vue中实现双向数据绑定的指令是 ______。",
      answer: "v-model"
    },

    {
      id: 19,
      type: "GapFilling",
      content: "Vue 3中引入的新API叫做 ______ API。",
      answer: "Composition"
    },

    {
      id: 20,
      type: "GapFilling",
      content: "Vue的官方状态管理库叫做 ______。",
      answer: "Vuex"
    },
    {
      id: 21,
      type: "AnswerQuestion",
      content: "解释 Vue 的虚拟 DOM 及其优势。",
      answer: "虚拟 DOM 是内存中的轻量级 DOM 表示，Vue 通过 diff 算法比较新旧虚拟 DOM 的差异，然后高效地更新真实 DOM，减少直接操作 DOM 的性能开销，提升渲染效率。"
    },
    {
      id: 22,
      type: "AnswerQuestion",
      content: "简述 Vue 的生命周期钩子函数及其作用。",
      answer: "Vue 的生命周期钩子函数包括 created、mounted、updated 和 destroyed 等，分别在实例创建、挂载、更新和销毁时触发，用于执行特定阶段的逻辑操作。"
    },
    {
      id: 23,
      type: "AnswerQuestion",
      content: "解释 Vue 中 computed 和 watch 的区别。",
      answer: "computed 用于计算属性，具有缓存特性，依赖数据变化时才会重新计算；watch 用于监听数据变化，适合执行异步或开销较大的操作。"
    },
    {
      id: 24,
      type: "AnswerQuestion",
      content: "简述 Vue 3 的 Composition API 相比 Options API 的优势。",
      answer: "Composition API 提供更好的逻辑复用能力、更灵活的代码组织方式、更友好的 TypeScript 支持，以及更清晰的代码结构，特别适合复杂组件开发。"
    },
  ],
});

// 检查题目是否已回答
const isQuestionAnswered = (questionId: number) => {
  const answer = userAnswers.value[questionId];
  if (Array.isArray(answer)) {
    return answer.length > 0;
  }
  return answer !== undefined && answer !== null && answer !== '';
};

// 按题型分组
const groupedQuestions = computed(() => {
  const groups: Record<string, Question[]> = {};
  exam.value.questions.forEach((question) => {
    if (!groups[question.type]) {
      groups[question.type] = [];
    }
    groups[question.type].push(question);
  });
  return groups;
});

// 映射题型到中文名称
const questionTypeLabels: Record<string, string> = {
  SingleChoice: "单选题",
  MultipleChoice: "多选题",
  GapFilling: "填空题",
  AnswerQuestion: "问答题",
};

// 滚动到指定题目
const scrollToQuestion = (questionId: number) => {
  currentQuestionId.value = questionId;
  const element = document.getElementById(`question-${questionId}`);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  }
};

// 切换单选题选项
const toggleSingleChoice = (questionId: number, option: string) => {
  if (userAnswers.value[questionId] === option) {
    console.log('点击已选中的选项，取消选择'+questionId);
    // 如果点击已选中的选项，则取消选择
    userAnswers.value[questionId] = '';
  } else {
    userAnswers.value[questionId] = option;
  }
};

// 切换多选题选项
const toggleMultipleChoice = (questionId: number, option: string) => {
  if (!Array.isArray(userAnswers.value[questionId])) {
    userAnswers.value[questionId] = [];
  }
  
  const index = (userAnswers.value[questionId] as string[]).indexOf(option);
  if (index === -1) {
    (userAnswers.value[questionId] as string[]).push(option);
  } else {
    (userAnswers.value[questionId] as string[]).splice(index, 1);
  }
};

// 处理填空题和问答题变化
const handleInputChange = (questionId: number) => {
  // 这里不需要额外处理，v-model已经自动更新了userAnswers
  // 只是为了触发答题卡状态更新
};

// 提交试卷并计算分数
const submitExam = () => {
  let score = 0;
  exam.value.questions.forEach((question) => {
    const userAnswer = userAnswers.value[question.id];
    if (question.type === "SingleChoice" || question.type === "GapFilling") {
      if (userAnswer === question.answer) {
        score++;
      }
    } else if (question.type === "MultipleChoice") {
      if (
        Array.isArray(userAnswer) &&
        JSON.stringify(userAnswer.sort()) === JSON.stringify((question.answer as string[]).sort())
      ) {
        score++;
      }
    }
    // 问答题略过评分，或自行补充评分逻辑
  });

  // 清除本地存储中的试卷数据 
  localStorage.clear();
  ElMessageBox.confirm(`您做对了：${score}/${exam.value.questions.length}`,'提示框',{
      confirmButtonText: '确认',
      type: 'warning',
    });
};

// 保存试卷
const saveExam = () => {
  const savedAnswers = Object.keys(userAnswers.value).map(questionId => ({
    questionId: parseInt(questionId),
    userAnswer: userAnswers.value[questionId]
  }));

  localStorage.setItem('savedExam', JSON.stringify(savedAnswers));
  ElMessageBox.confirm('试卷已保存','提示框',{
      confirmButtonText: '确认',
      type: 'success',
    });
};

// 页面加载时，尝试从本地加载已保存的答案
onMounted(() => {
  const savedAnswers = JSON.parse(localStorage.getItem('savedExam') || '[]');
  savedAnswers.forEach((answer: { questionId: number, userAnswer: string | string[] }) => {
    userAnswers.value[answer.questionId] = answer.userAnswer;
  });
  
  // 初始化多选题的答案数组
  exam.value.questions.forEach(question => {
    if (question.type === 'MultipleChoice' && !Array.isArray(userAnswers.value[question.id])) {
      userAnswers.value[question.id] = [];
    }
  });
});
</script>

<style scoped>
.question-bank-container {
  width: 60%;
  display: flex;
  height: calc(100vh - 40px);
  gap: 20px;
  padding: 20px;
  background-color: #f5f7fa;
}

#content{
  overflow-y: auto;
}
/* 左侧答题卡 */
.answer-card {
  width: 280px;
  flex-shrink: 0;
}

.question-content {
  flex: 1;
}

.el-card{
  height: 100%;
  overflow: auto;
}

/* 答题卡滚动区域 */
.el-card .is-always-shadow {
  height: calc(100% - 40px);
  overflow-y: auto;
}

.card-title, .exam-title {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
  font-size: 20px;
  font-weight: bold;
}

.exam-description {
  color: #666;
  margin-bottom: 20px;
  padding: 0 15px;
  line-height: 1.6;
}

.question-type-section {
  margin-bottom: 20px;
}

.question-type-title {
  font-size: 16px;
  color: #409EFF;
  margin-bottom: 10px;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
}

.question-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.question-item {
  width: 36px;
  height: 36px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  background-color: #f5f7fa;
  border: 1px solid #dcdfe6;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
}

.question-item:hover {
  background-color: #ecf5ff;
  border-color: #c6e2ff;
}

.question-item.answered {
  background-color: #409EFF;
  color: white;
  border-color: #409EFF;
}

.question-item.current {
  border: 2px solid #67c23a;
  box-shadow: 0 0 5px rgba(103, 194, 58, 0.5);
}

.section-title {
  font-size: 18px;
  color: #333;
  margin: 25px 0 15px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebeef5;
}

.question-wrapper {
  margin-bottom: 25px;
  padding: 15px;
  border-radius: 4px;
  background-color: #fff;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.question-wrapper:hover {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.question-header {
  margin-bottom: 15px;
  line-height: 1.6;
}

.question-number {
  color: #409EFF;
  margin-right: 8px;
}

/* 左侧侧题目 */
.question-content-text {
  color: #333;
}

.question-options {
  margin-left: 20px;
}

/* 增加选项间距 */
.option-item {
  display: block;
  margin: 12px 0;  /* 从8px增加到12px */
  color: #606266;
  padding: 8px;
  border-radius: 4px;
  transition: background-color 0.2s;
}

.option-item:hover {
  background-color: #f5f7fa;
}

.gap-filling {
  margin-left: 20px;
  width: 50%;
}

.answer-question {
  margin-left: 20px;
}

.editor {
  height: 200px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.action-buttons {
  display: flex;
  justify-content: center; 
  margin-top: 30px;
  gap: 20px;
}

.el-card {
  height: 100%;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}
</style>